const fs = require('fs')

module.exports = {
  /**
   * 校验文件是否存在
   * @param path 文件路径
   * @returns {Promise<unknown>}
   */
  fileExist(path) {
    return new Promise((resolve, reject) => {
      fs.access(path, (err) => {
        if (err) {
          resolve(false)
        } else {
          resolve(true)
        }
      })
    })
  },
  writeData(path, text) {
    return new Promise((resolve, reject) => {
      fs.open(path, 'w', function (err, fd) {
        if (err) {
          reject(err)
        } else {
          const str = typeof text === 'object' ? JSON.stringify(text) : text
          fs.writeFile(path, str, (err) => {
            if (err) {
              reject(err)
            } else {
              resolve()
            }
          });
        }
      });
    })
  },
  readData(path) {
    return new Promise((resolve, reject) => {
      fs.readFile(path, (err, data) => {
        if (err) {
          reject(err)
        } else {
          resolve(data)
        }
      });
    })
  },
  removeFile(path) {
    return new Promise((resolve, reject) => {
      fs.unlink(path, (err) => {
        if (!err || err.errno == -2) {
          resolve()
        } else {
          reject(err)
        }
      });
    })
  }
}
